package com.hanson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.common.bean.GoodsRuleItemBean;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.GoodsAttrBean;
import com.hanson.entity.GoodsAttrValueBean;
import com.hanson.entity.GoodsBean;
import com.hanson.entity.GroupGoodsBean;
import com.hanson.mapper.GoodsAttrBeanMapper;
import com.hanson.mapper.GoodsAttrValueBeanMapper;
import com.hanson.mapper.GroupGoodsBeanMapper;
import com.hanson.mapper.UserBeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class GroupGoodsService {
    @Autowired
    private GroupGoodsBeanMapper groupGoodsBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private GoodsAttrBeanMapper goodsAttrBeanMapper;
    @Autowired
    private SmsService smsService;

    public GoodsBean getRules(Integer id) {
        GroupGoodsBean returnBean = groupGoodsBeanMapper.selectByPrimaryKey(id);
        if (null == returnBean) {
            throw new BusinessException("ID不正确");
        }
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setId(returnBean.getId());
        goodsBean.setSpecType(null == returnBean.getSpecType() ? "0" : String.valueOf(returnBean.getSpecType()));
        List<GoodsAttrBean> goodsAttrBeanList = goodsAttrBeanMapper.selectByGoodsId(id, 2);
        if (CollectionUtils.isNotEmpty(goodsAttrBeanList)) {
            List<GoodsRuleItemBean> items = new ArrayList<>();
            goodsAttrBeanList.stream().forEach(c -> {
                GoodsRuleItemBean goodsRuleItemBean = new GoodsRuleItemBean();
                goodsRuleItemBean.setValue(c.getAttrName());
                goodsRuleItemBean.setDetail(Arrays.asList(c.getAttrValues().split(",")));
                goodsRuleItemBean.setDetailValue("");
                items.add(goodsRuleItemBean);
            });
            goodsBean.setItems(items);
        }else {
            goodsBean.setItems(new ArrayList<>());
        }
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsId(id, 2);
        if (CollectionUtils.isNotEmpty(goodsAttrValueBeanList)) {
            //单规格
            if (goodsBean.getSpecType().equals("0")) {
                goodsBean.setAttr(JSONObject.parseObject(goodsAttrValueBeanList.get(0).getDetail(), GoodsAttrValueBean.class));
                goodsBean.setAttrs(new ArrayList<>());
            } else {
                List<JSONObject> attrs = new ArrayList<>();
                goodsAttrValueBeanList.stream().forEach(c -> {
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(c.getDetail());
                    jsonObject.put("suk", c.getSuk());
                    attrs.add(jsonObject);
                });
                goodsBean.setAttrs(attrs);
                goodsBean.setAttr(new GoodsAttrValueBean());
            }
        }else {
            goodsBean.setAttr(new GoodsAttrValueBean());
            goodsBean.setAttrs(new ArrayList<>());
        }
        return goodsBean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void setRules(GroupGoodsBean groupGoodsBean) {
        GroupGoodsBean returnBean = groupGoodsBeanMapper.selectByPrimaryKey(groupGoodsBean.getId());
        if (null == returnBean) {
            throw new BusinessException("ID不正确");
        }
        returnBean.setUpdateDate(new Date());
        returnBean.setSpecType(null == groupGoodsBean.getSpecType() ? 0 : groupGoodsBean.getSpecType());
        groupGoodsBeanMapper.updateByPrimaryKey(returnBean);

        goodsAttrBeanMapper.deleteByGoodsId(groupGoodsBean.getId(), 2);
        goodsAttrValueBeanMapper.deleteByGoodsId(groupGoodsBean.getId(), 2);
        /***商品规格 但规格的为空*/
        if (CollectionUtils.isNotEmpty(groupGoodsBean.getItems())) {
            groupGoodsBean.getItems().stream().forEach(c -> {
                GoodsAttrBean goodsAttrBean = new GoodsAttrBean();
                goodsAttrBean.setGoodsId(groupGoodsBean.getId());
                goodsAttrBean.setAttrName(c.getValue());
                goodsAttrBean.setAttrValues(String.join(",", c.getDetail()));
                goodsAttrBean.setGoodsType(2);
                goodsAttrBeanMapper.insert(goodsAttrBean);
            });
        }

        /**商品规格组合结果**/
        if (CollectionUtils.isNotEmpty(groupGoodsBean.getAttrs())) {
            for (JSONObject c : groupGoodsBean.getAttrs()) {
                GoodsAttrValueBean goodsAttrValueBean = new GoodsAttrValueBean();
                if (c.containsKey("detail")) {
                    JSONObject detailJson = c.getJSONObject("detail");
                    StringBuffer sukSb = new StringBuffer();
                    for (Map.Entry<String, Object> entry : detailJson.entrySet()) {
                        sukSb.append(entry.getValue()).append(",");
                    }
                    goodsAttrValueBean.setSuk(sukSb.substring(0, sukSb.length() - 1).toString());
                }
                Integer stockValue = c.getInteger("stock");
                stockValue = stockValue == null ? 0 : stockValue;
                goodsAttrValueBean.setDetail(JSON.toJSONString(c));
                goodsAttrValueBean.setGoodsId(groupGoodsBean.getId());
                goodsAttrValueBean.setStock(stockValue);
                goodsAttrValueBean.setVipPrice(BusinessUtil.getDbAmount(c.getString("vipPrice")) + "");
                goodsAttrValueBean.setPrice(BusinessUtil.getDbAmount(c.getString("price")) + "");
                goodsAttrValueBean.setSpreadMoney(BusinessUtil.getDbAmount(c.getString("spreadMoney")) + "");
                goodsAttrValueBean.setSpreadChildMoney(BusinessUtil.getDbAmount(c.getString("spreadChildMoney")) + "");
                goodsAttrValueBean.setImage(c.getString("image"));
                goodsAttrValueBean.setGoodsType(2);
                goodsAttrValueBeanMapper.insert(goodsAttrValueBean);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(GroupGoodsBean groupGoodsBean) {
        if (null == groupGoodsBean.getGoodsId()) {
            throw new BusinessException("商品ID不能为空");
        }
        List<GroupGoodsBean> groupGoodsBeanList = groupGoodsBeanMapper.selectByGoodsId(groupGoodsBean.getGoodsId());
        if (CollectionUtils.isNotEmpty(groupGoodsBeanList)) {
            throw new BusinessException("当前商品已在拼团中，不能重复添加");
        }
        if (groupGoodsBean.getGroupNum() < 2) {
            throw new BusinessException("成团数量至少2个人");
        }
        groupGoodsBean.setCreateDate(new Date());
        groupGoodsBean.setStatus(0);
        groupGoodsBean.setIsShow(1);
        groupGoodsBean.setGoodsPrice(BusinessUtil.getDbAmount(groupGoodsBean.getWebGoodsPrice()));
        groupGoodsBean.setGroupPrice(BusinessUtil.getDbAmount(groupGoodsBean.getWebGroupPrice()));
        groupGoodsBean.setSpecType(0);
        groupGoodsBeanMapper.insert(groupGoodsBean);
        //设置默认规格
        GoodsAttrValueBean goodsAttrValueBean = new GoodsAttrValueBean();
        String detailTemplate = "{\"spreadChildMoney\":\"0\",\"price\":\"%s\",\"vipPrice\":\"%s\",\"stock\":\"9999\",\"spreadMoney\":\"0\"}";
        goodsAttrValueBean.setDetail(String.format(detailTemplate,groupGoodsBean.getWebGroupPrice(),groupGoodsBean.getWebGroupPrice()));
        goodsAttrValueBean.setGoodsId(groupGoodsBean.getId());
        goodsAttrValueBean.setStock(9999);
        goodsAttrValueBean.setVipPrice(groupGoodsBean.getGroupPrice() + "");
        goodsAttrValueBean.setPrice(groupGoodsBean.getGroupPrice() + "");
        goodsAttrValueBean.setSpreadMoney("0");
        goodsAttrValueBean.setSpreadChildMoney("0");
        goodsAttrValueBean.setGoodsType(2);
        goodsAttrValueBeanMapper.insert(goodsAttrValueBean);
        smsService.partnerGoodsNotify(userBeanMapper.getAllPartner(), groupGoodsBean.getGoodsName(), groupGoodsBean.getWebGoodsPrice());
    }

    public void modify(GroupGoodsBean groupGoodsBean) {
        if (null == groupGoodsBean.getGoodsId()) {
            throw new BusinessException("商品ID不能为空");
        }
        if (groupGoodsBean.getGroupNum() < 2) {
            throw new BusinessException("成团数量至少2个人");
        }
        GroupGoodsBean returnBean = groupGoodsBeanMapper.selectByPrimaryKey(groupGoodsBean.getId());
        if (null != returnBean) {
            List<GroupGoodsBean> groupGoodsBeanList = groupGoodsBeanMapper.selectByGoodsId(groupGoodsBean.getGoodsId());
            if (CollectionUtils.isNotEmpty(groupGoodsBeanList) && !groupGoodsBeanList.get(0).getGoodsId().equals(returnBean.getGoodsId())) {
                throw new BusinessException("当前商品已在拼团中，不能重复添加");
            }
            groupGoodsBean.setUpdateDate(new Date());
            groupGoodsBean.setCreateDate(returnBean.getCreateDate());
            groupGoodsBean.setStatus(returnBean.getStatus());
            groupGoodsBean.setIsShow(returnBean.getIsShow());
            groupGoodsBean.setGoodsPrice(BusinessUtil.getDbAmount(groupGoodsBean.getWebGoodsPrice()));
            groupGoodsBean.setGroupPrice(BusinessUtil.getDbAmount(groupGoodsBean.getWebGroupPrice()));
            groupGoodsBean.setSales(returnBean.getSales());
            groupGoodsBean.setJoinNum(returnBean.getJoinNum());
            groupGoodsBean.setGroupedNum(returnBean.getGroupedNum());
            groupGoodsBean.setViewNum(returnBean.getViewNum());
            groupGoodsBeanMapper.updateByPrimaryKey(groupGoodsBean);
        }
    }

    public void mofiySimpleData(GroupGoodsBean groupGoodsBean) {
        groupGoodsBean.setUpdateDate(new Date());
        groupGoodsBeanMapper.updateByPrimaryKey(groupGoodsBean);
    }

    public GroupGoodsBean selectById(Integer id) {
        GroupGoodsBean groupGoodsBean = groupGoodsBeanMapper.selectByPrimaryKey(id);
        if (null != groupGoodsBean) {
            groupGoodsBean.setWebGoodsPrice(BusinessUtil.getWebAmount(groupGoodsBean.getGoodsPrice()));
            groupGoodsBean.setWebGroupPrice(BusinessUtil.getWebAmount(groupGoodsBean.getGroupPrice()));
        }
        return groupGoodsBean;
    }

    public void fillAttrs(GroupGoodsBean groupGoodsBean){
        if(null == groupGoodsBean){
            return;
        }
        List<GoodsAttrBean> goodsAttrBeanList = goodsAttrBeanMapper.selectByGoodsId(groupGoodsBean.getId(),2);
        if (CollectionUtils.isNotEmpty(goodsAttrBeanList)) {
            List<GoodsRuleItemBean> items = new ArrayList<>();
            goodsAttrBeanList.stream().forEach(c -> {
                GoodsRuleItemBean goodsRuleItemBean = new GoodsRuleItemBean();
                goodsRuleItemBean.setValue(c.getAttrName());
                goodsRuleItemBean.setDetail(Arrays.asList(c.getAttrValues().split(",")));
                goodsRuleItemBean.setDetailValue("");
                items.add(goodsRuleItemBean);
            });
            groupGoodsBean.setItems(items);
        }
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsId(groupGoodsBean.getId(),2);
        if (CollectionUtils.isNotEmpty(goodsAttrValueBeanList)) {
            //单规格
            log.info("groupGoodsBean.getSpecType()={}",groupGoodsBean.getSpecType());
            if (null == groupGoodsBean.getSpecType() || groupGoodsBean.getSpecType() == 0) {
                groupGoodsBean.setAttr(JSONObject.parseObject(goodsAttrValueBeanList.get(0).getDetail(), GoodsAttrValueBean.class));
                groupGoodsBean.setAttrs(new ArrayList<>());
            } else {
                List<JSONObject> attrs = new ArrayList<>();
                goodsAttrValueBeanList.stream().forEach(c -> {
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(c.getDetail());
                    jsonObject.put("suk", c.getSuk());
                    attrs.add(jsonObject);
                });
                groupGoodsBean.setAttrs(attrs);
                groupGoodsBean.setAttr(new GoodsAttrValueBean());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) {
        groupGoodsBeanMapper.deleteByPrimaryKey(id);
        goodsAttrBeanMapper.deleteByGoodsId(id, 2);
        goodsAttrValueBeanMapper.deleteByGoodsId(id, 2);
    }

    public Page<GroupGoodsBean> listGroupGoods(Page<GroupGoodsBean> page, GroupGoodsBean groupGoodsBean) {
        List<GroupGoodsBean> list = groupGoodsBeanMapper.listGroupGoods(page, groupGoodsBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebGroupPrice(BusinessUtil.getWebAmount(c.getGroupPrice()));
            });
        }
        return page.setRecords(list);
    }

    public void updateIsShow(int isShow, int id) {
        groupGoodsBeanMapper.updateIsShow(isShow, id);
    }

    public List<GroupGoodsBean> getGroupGoods() {
        List<GroupGoodsBean> list = groupGoodsBeanMapper.selectCurrentTimeData();
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebGroupPrice(BusinessUtil.getWebAmount(c.getGroupPrice()));
            });
        }
        return list;
    }

    public Page<GroupGoodsBean> getGroupGoodsPage(int page, int limit) {
        Page<GroupGoodsBean> pageInfo = new Page<>(page, limit);
        List<GroupGoodsBean> list = groupGoodsBeanMapper.listPage(pageInfo);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebGroupPrice(BusinessUtil.getWebAmount(c.getGroupPrice()));
            });
        }
        return pageInfo.setRecords(list);
    }
}
